<?php
//    +----------------------------------------------------------------------
//    | Copyright (c) 2015-2035 http://www.hdphp.cn All rights reserved.
//    | Licensed ( http://www.hdphp.cn/licenses/ )
//    | Author: Jack <sophia2152@qq.com>
//    | 官方网址: http://www.hdphp.cn
//    | 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
//    | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
//    +----------------------------------------------------------------------
namespace app\services\system\admin;

use app\Request;
use app\services\BaseServices;
use app\dao\system\admin\SystemAdminRoleDao;
use app\services\system\SystemMenusServices;
use hdphp\services\CacheService;
use hdphp\exceptions\AuthException;
use hdphp\utils\ApiCode;

/**
 * Class：SystemAdminRoleServices
 * 创建人：Jack
 * 创建时间：2023/3/21 7:48 PM
 * @package app\services\system\admin
 * @mixin SystemAdminRoleDao
 */
class SystemAdminRoleServices extends BaseServices
{
    /**
     * 当前管理员权限缓存前缀
     */
    const ADMIN_RULES_LEVEL = 'Admin_rules_level_';

    /**
     * SystemAdminRoleServices constructor.
     * @param SystemAdminRoleDao $dao
     */
    public function __construct(SystemAdminRoleDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 注释：获取权限
     * 创建人：Jack
     * 创建时间：2023/3/23 16:52
     * @param array $where
     * @param string $field
     * @param string $key
     * @return array
     */
    public function getRoleArray(array $where = [], string $field = '', string $key = '')
    {
        return $this->dao->getRoule($where, $field, $key);
    }
    
    /**
     * 注释：后台验证权限
     * 创建人：Jack
     * 创建时间：2023/3/24 16:53
     * @param Request $request
     * @return true|void
     */
    public function verifiAuth(Request $request)
    {
        $rule = str_replace('adminapi/', '', trim(strtolower($request->rule()->getRule())));
        if (in_array($rule, ['setting/admin/logout', 'menuslist'])) {
            return true;
        }
        $auth = $this->getAllRoles(2);
        // 验证访问接口是否存在
        if (!in_array($rule, array_map(function ($item) {
            return trim(strtolower(str_replace(' ', '', $item)));
        }, array_column($auth, 'api_url')))) {
            return true;
        }
        $auth = $this->getRolesByAuth($request->userInfo()['roles'], 2);
        $method = trim(strtolower($request->method()));
        // 验证访问接口是否有权限
        if (empty(array_filter($auth, function ($item) use ($rule, $method) {
            if (trim(strtolower($item['api_url'])) === $rule && $method === trim(strtolower($item['methods'])))
                return true;
        }))) {
            throw new AuthException(ApiCode::ERR_AUTH);
        }
    }

    /**
     * 注释：获取所有权限
     * 创建人：Jack
     * 创建时间：2023/3/24 16:53
     * @param int $auth_type
     * @param string $cachePrefix
     * @return array|bool|mixed|null
     */
    public function getAllRoles(int $auth_type = 1, string $cachePrefix = self::ADMIN_RULES_LEVEL)
    {
        $cacheName = md5($cachePrefix . '_' . $auth_type . '_ALl');
        return CacheService::redisHandler('system_menus')->remember($cacheName, function () use ($auth_type) {
            /** @var SystemMenusServices $menusService */
            $menusService = app()->make(SystemMenusServices::class);
            return $menusService->getColumn([['auth_type', '=', $auth_type]], 'api_url,methods');
        });
    }

    /**
     * 注释：获取指定权限
     * 创建人：Jack
     * 创建时间：2023/3/24 16:56
     * @param array $rules
     * @param int $auth_type
     * @param int $type
     * @param string $cachePrefix
     * @return array|bool|mixed|null
     */
    public function getRolesByAuth(array $rules, int $auth_type = 1, string $cachePrefix = self::ADMIN_RULES_LEVEL)
    {
        if (empty($rules)) return [];
        $cacheName = md5($cachePrefix . '_' . $auth_type . '_' . implode('_', $rules));
        return CacheService::redisHandler('system_menus')->remember($cacheName, function () use ($rules, $auth_type) {
            /** @var SystemMenusServices $menusService */
            $menusService = app()->make(SystemMenusServices::class);
            return $menusService->getColumn([['menu_id', 'IN', $this->getRoleIds($rules)], ['auth_type', '=', $auth_type]], 'api_url,methods');
        });
    }

    /**
     * 注释：获取权限id
     * 创建人：Jack
     * 创建时间：2023/3/24 16:59
     * @param array $rules
     * @return false|string[]
     */
    public function getRoleIds(array $rules)
    {
        $rules = $this->dao->getColumn([['id', 'IN', $rules], ['status', '=', '1']], 'rules', 'id');
        return array_unique(explode(',', implode(',', $rules)));
    }

}
